package com.fabrizio.dissociator;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class KGram {
    String[] prefix;
    LinkedHashMap<String, Integer> suffixToFrequencyMap;
    
    public KGram(String[] prefixList){
    	// initialize suffix list, copy incoming prefixes to KGram object instance
    	int i;
    	suffixToFrequencyMap = new LinkedHashMap<String, Integer>();
    	int prefixLength = prefixList.length;    	
    	prefix = new String[prefixLength];


    	for(i = 0; i < prefixLength; i++){
    	    prefix[i] = prefixList[i];	
    	}
    }
    
    public void addSuffix(String suffix /*, Integer multiplicity*/){
        int multiplicity= 0;
    	if(!suffixToFrequencyMap.isEmpty() && suffixToFrequencyMap.containsKey(suffix)){
    		multiplicity = suffixToFrequencyMap.get(suffix);
    	}

    	if(multiplicity > 0){
    	    suffixToFrequencyMap.put(suffix, multiplicity + 1);
    	} // first entry of this suffix
    	else {
            suffixToFrequencyMap.put(suffix, 1);          
    	}
    }
    
    
    public String generateNextWord(){
    	System.out.print("generateNextWord");
    	int i = 0;
    	int suffixMultSum = 0;
    	int numOfSuffixes = suffixToFrequencyMap.size();
    	Collection<Integer> suffixVals = suffixToFrequencyMap.values();
    	double[] weights = new double[numOfSuffixes];

    	// iterate suffix mapping table once to get sum of suffix frequencies, then once again
    	// to calculate the weights for the weighted random index generator.
    	for (Iterator<Integer> iterA = suffixVals.iterator(); iterA.hasNext();) {
    		suffixMultSum += iterA.next();
    	}
    	
    	for (Iterator<Integer> iterB = suffixVals.iterator(); iterB.hasNext();){
    		int currMultiplicity = iterB.next();
    	    weights[i] = currMultiplicity / suffixMultSum;
    	    i++;
    	}

    	// generate a weighted random index into the list of suffixVals based on
    	// frequency of the suffix, then get the corresponding suffix.
    	WeightedRandomNumberGenerator wrng = new WeightedRandomNumberGenerator(weights);
    	int randomSuffixIdx = wrng.next();
    	
        Collection<String> suffixes = suffixToFrequencyMap.keySet();
    	String[] suffixArr = suffixes.toArray(new String[0]);

    	return suffixArr[randomSuffixIdx];
    }
    
}
